#include "log.h"
#include <QFile>
#include "globals.h"
#include "sources/microfor.h"


void save(QString filename, QString message)
{
    QFile file(filename);
    if (!file.open(QIODevice::Append))
        if (!file.open(QIODevice::WriteOnly)) return;

    QString timestamp = QDateTime::currentDateTime().toString("[ d.MM.yyyy h:mm:ss ] - ");
    QString logString = timestamp + message;
    file.write(logString.toAscii());
}

void CLog::Process()
{
    if (path.isNull()) return;
    if (path.isEmpty()) return;
    foreach(CTechParameter *t,globals->parameters)
    {
        if (t->archFilename.isNull()) continue;
        if (t->archFilename.isEmpty()) continue;
        if (t->getStatus() != PS_NORMAL) continue;
        QString filename = path + "\\" + t->archFilename;
        double value = t->getValue();
        double ole_date = toOle(QDateTime::currentDateTime());
        save(filename,value,ole_date);
    }
}

void CLog::save(QString filename,double value, double ole_date)
{
    QFile file(filename);
    if (!file.open(QIODevice::Append))
        if (!file.open(QIODevice::WriteOnly)) return;

    TData data;
    data.date = ole_date;
    data.humidity = value;
    data.temperature = value;
    data.addition =0;
    QByteArray ba((const char *)&data,sizeof(TData));
    file.write(ba);
    file.close();
};

double CLog::toOle(QDateTime dtime)
{
    int days = dtime.date().daysTo(QDate(1899,12,30));
    int secs = dtime.secsTo(QDateTime(QDate::currentDate(),QTime(0,0,0,0)));
    double result = double(days);
    double drob = secs;
    drob /= 3600.0 * 24.0;
    result += drob;
    return -result;
};

